import axios from "axios";
import { useLoadingStore, useUserStore } from "@/stores/index";
import { storeToRefs } from "pinia";

const baseURL = import.meta.env.VITE_APP_BASE_URL
const timeout = 10000

const http = axios.create({
    baseURL,
    timeout
})


http.interceptors.request.use((config: any) => {
    const userStore = useUserStore()
    const { token } = storeToRefs(userStore)

    if (token) {
        config.headers['Authorization'] = token.value
    }

    const loadingStore = useLoadingStore()
    const { showLoading } = loadingStore
    showLoading()
    return config
})

http.interceptors.response.use((response: any) => {
    const userStore = useUserStore()
    const { clearToken } = userStore;
    const loadingStore = useLoadingStore()
    const { closeLoading } = loadingStore
    closeLoading()
    if (response.data.code !== 200 && response.config.url !== '/sys/user/captcha') {
        ElMessage({
            type: "warning",
            message: response.data.msg,
        });
        if (response.data.code === 401) {
            clearToken()
        }
    }
    return response.data
}, (error: any) => {
    ElMessage.error("网络错误，请稍后再试");
})
export { baseURL }
export default http